import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class StreamDemo extends StatefulWidget {
  @override
  _StreamDemoState createState() => _StreamDemoState();
}

class _StreamDemoState extends State<StreamDemo> {
  int x = 0;
  late StreamController<String> streamController;
  late StreamSubscription<String> subscription;

  @override
  void initState() {
    super.initState();
    streamController = StreamController();
    // subscription = streamController.stream.listen((event) {
    //   print(event);
    // },
    // onError: (e) {
    //   print(e);
    // },
    // onDone: () {
    //   print("done");
    // },
    // );
    streamController.add("event1");
    streamController.sink.add("event2");
    // streamController.addError("error");

    // Stream<String> stream = Stream.fromFuture(delayData());
    // setState(() {
    //
    // });
  }

  Future<String> delayData() async {
    await Future.delayed(new Duration(seconds: 3));
    return "abc";
  }

  @override
  void dispose() {
    streamController.close();
    // subscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(title: const Text("Stream"),),
      body: StreamBuilder<String> (
        initialData: "1",
        stream: streamController.stream,
        builder: (ctx, AsyncSnapshot<String> a) {
          return Center(child: Column(
            mainAxisAlignment:MainAxisAlignment.center, children: [
            Text(a.requireData),
            IconButton(onPressed: (){
              x++;
              streamController.add("$x");
              }, icon: Icon(CupertinoIcons.info_circle_fill))
          ],),);
        },
      ),
    );
  }
}
